package org.bikelab.se3.rdf.reader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;

import org.semanticweb.yars.nx.Literal;
import org.semanticweb.yars.nx.Node;
import org.semanticweb.yars.nx.Resource;

import com.hp.hpl.jena.graph.Triple;

import de.fuberlin.wiwiss.ng4j.NamedGraph;
import de.fuberlin.wiwiss.ng4j.NamedGraphSet;
import de.fuberlin.wiwiss.ng4j.impl.NamedGraphSetImpl;

public class TrigParser implements Iterator<Node[]> {
	NamedGraphSet graphset = new NamedGraphSetImpl();
	
	Iterator<NamedGraph> graphs;
	
	Iterator<Triple> graphIter;
	
	NamedGraph graph;
	
	public TrigParser(InputStream in) {
		graphset.read(in, "TRIG", null);
		graphs = graphset.iterator();
		getNextGraph();
	}
	
	public void getNextGraph() {
		if(graphs.hasNext()) {
			graph = graphs.next();
			graphIter = graph.find(com.hp.hpl.jena.graph.Node.ANY, com.hp.hpl.jena.graph.Node.ANY, com.hp.hpl.jena.graph.Node.ANY);
		} else {
			graphIter = null;
		}
	}
	
	public Node[] toNodes(Triple t) {
		Node[] nodes = new Node[3];
		nodes[0] = new Resource(t.getSubject().getURI());
		nodes[1] = new Resource(t.getPredicate().getURI());
		if(t.getObject().isURI()) {
			nodes[2] = new Resource(t.getObject().getURI());
		} else {
			nodes[2] = new Literal(t.getObject().getURI());
		}
		return nodes;
	}

	@Override
	public boolean hasNext() {
		if(graphIter == null) {
			graphset.close();
			return false;
		}
		while(!graphIter.hasNext()) {
			getNextGraph();
			if(graphIter == null) {
				graphset.close();
				return false;
			}
		}
		return true;
	}
	
	@Override
	public Node[] next() {
		Triple t = graphIter.next();
		
		Node[] nodes = new Node[4];
		nodes[0] = new Resource(t.getSubject().getURI());
		nodes[1] = new Resource(t.getPredicate().getURI());
		if(t.getObject().isURI()) {
			nodes[2] = new Resource(t.getObject().getURI());
		} else {
			nodes[2] = new Literal(t.getObject().getLiteral().toString());
		}
		nodes[3] = new Resource(graph.getGraphName().getURI());
		
		return nodes;
	}

	@Override
	public void remove() {
	}
	
	public static void main(String ... args) {
		try {
			Iterator<Node[]> i = new TrigParser(new FileInputStream(new File("res/tmp/" + "cell-map_0.trig")));
			while(i.hasNext()) {
				for(Node n : i.next()) {
					System.out.print(n.toN3() + " ");
				}
				System.out.println();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
